from backend.services.base import BaseService
from backend.services.serializers import (DeliveryObjectSerializer, InvoiceObjectSerializer,
                                          BuyOrderPaymentObjectSerializer)
from backend.biz import DeliveryBiz, InvoiceBiz, PaymentBiz
from backend.po.take_delivery import TakeDelivery
from backend.po.recv_invoice import RecvInvoice
from backend.po.payment4buy import Payment4BuyOrder
from backend.services import BuyOrderService


class ForeignBuyOrderService(BaseService):
    def __init__(self, obj_cls, obj_ser_cls, biz):
        super().__init__(obj_cls, obj_ser_cls, biz)
        self.buy_order_svc = BuyOrderService()

    @staticmethod
    def __adapter_order(data):
        if data['buy_order'] is not None:
            data['buy_order'] = data['buy_order']['id']

    def preform_create(self, data, *args, **kwargs):
        self.__adapter_order(data)
        return super().preform_create(data, *args, **kwargs)

    def create(self, obj):
        if obj.buy_order is not None and obj.buy_order.id == 0:
            new_order = self.buy_order_svc.create(obj.buy_order)
            obj.buy_order = new_order

        return super().create(obj)

    def preform_update(self, data, *args, **kwargs):
        self.__adapter_order(data)
        return super().preform_update(data, *args, **kwargs)

    def update(self, obj):
        if obj.buy_order is not None:
            if obj.buy_order.id == 0:
                new_order = self.buy_order_svc.create(obj.buy_order)
                obj.buy_order = new_order
            else:
                self.buy_order_svc.update(obj.buy_order)

        return super().update(obj)


class DeliveryService(ForeignBuyOrderService):
    def __init__(self):
        super().__init__(TakeDelivery, DeliveryObjectSerializer, DeliveryBiz())


class InvoiceService(ForeignBuyOrderService):
    def __init__(self):
        super().__init__(RecvInvoice, InvoiceObjectSerializer, InvoiceBiz())


class PaymentService(ForeignBuyOrderService):
    def __init__(self):
        super().__init__(Payment4BuyOrder, BuyOrderPaymentObjectSerializer, PaymentBiz())
